package com.ribbon;

import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.ILoadBalancer;
import com.netflix.loadbalancer.Server;

import java.util.List;

/**
 * @BelongsProject: springcloud
 * @BelongsPackage: com.ribbon
 * @Author: LiMengshuai
 * @CreateTime: 2019-07-24 11:25
 * @Description: ${Description}
 */
public class FiveRoundRule extends AbstractLoadBalancerRule {

    private int total=0;
    private int currentindex=0;

    public Server choose(ILoadBalancer lb, Object key) {
        if (lb == null) {
            return null;
        } else {
            Server server = null;

            while(server == null) {
                if (Thread.interrupted()) {
                    return null;
                }

                List<Server> upList = lb.getReachableServers();
                List<Server> allList = lb.getAllServers();
                int serverCount = allList.size();
                if (serverCount == 0) {
                    return null;
                }

                if(total<5){
                    server = upList.get(currentindex);
                    total++;
                }else{
                    total =0;
                    currentindex++;
                    if(currentindex >=upList.size())
                    currentindex=0;
                }

                if (server == null) {
                    Thread.yield();
                } else {
                    if (server.isAlive()) {
                        return server;
                    }
                    server = null;
                    Thread.yield();
                }
            }
            return server;
        }
    }

    public Server choose(Object key) {
        return this.choose(this.getLoadBalancer(), key);
    }

    public void initWithNiwsConfig(IClientConfig clientConfig) {
    }
}
